
/**
 * UserService
 *
 * @author glory.xu
 */


import { Service } from 'egg';


export class User extends Service {

  // get userList
  public async getUserList() {
    const { ctx } = this;
    const local: any = await ctx.model.User.findAll({
      raw: true,
    });

    return local;
  }

  public async getList({ limit = 10, offset = 1, opt = {} }) {
    const { ctx } = this;
    const { count, rows } = await ctx.model.User.findAndCountAll({
      where: { ...opt },
      limit,
      offset,
      order: [[ 'id', 'DESC' ]],
    });

    const result = { total: count, rows };
    return result;

  }

  public async getByUserName(name) {
    const { ctx } = this;
    const result = await ctx.model.User.findOne({
      where: {
        name,
      },
    });
    return result;
  }


  public async get(id) {
    const { ctx } = this;
    const result = await ctx.model.User.findOne({
      where: {
        id,
      },
    });
    return result;
  }

  public async edit(data = {}, id) {
    const { ctx } = this;
    ctx.model.User.update({
      ...data,
    }, {
      where: {
        id,
      },
    });
  }

  public async create(data = {}) {
    const { ctx } = this;
    const res = await ctx.model.User.create({
      ...data,
    });
    return res;
  }

  public async update(data = {}, id) {
    const { ctx } = this;
    ctx.model.User.update({
      ...data,
    }, {
      where: {
        id,
      },
    });
  }

  public async destroy(id) {
    const { ctx } = this;
    ctx.model.User.destroy({
      where: {
        id,
      },
    });
  }


}

export default User;
